package com.rop.znyx.activity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rop.znyx.activity.mapper.SecKillSkuMapper;
import com.rop.znyx.activity.service.SecKillSkuService;
import com.rop.znyx.product.ProductFeignClient;
import com.rop.znyx.enums.SkuType;
import com.rop.znyx.model.activity.SecKillSku;
import com.rop.znyx.vo.activity.SecKillSkuQueryVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

/**
 * Created with IntelliJ IDEA
 * User: Rop
 * Date: 2023/7/11
 * Time: 9:45
 * Description:
 */

@Slf4j
@Service
@RequiredArgsConstructor
public class SecKillSkuServiceImpl extends ServiceImpl<SecKillSkuMapper, SecKillSku> implements SecKillSkuService {

    private final ProductFeignClient productFeignClient;

    /**
     * 获取分页列表
     */
    @Override
    public IPage<SecKillSku> selectPage(Page<SecKillSku> pageParam, SecKillSkuQueryVo SecKillSkuQueryVo) {
        // 查询条件
        Long SecKillId = SecKillSkuQueryVo.getSecKillId();
        Long SecKillTimeId = SecKillSkuQueryVo.getSecKillTimeId();

        LambdaQueryWrapper<SecKillSku> queryWrapper = new LambdaQueryWrapper<>();
        Optional.ofNullable(SecKillId).ifPresent(t -> queryWrapper.eq(SecKillSku::getSecKillId, SecKillId));
        Optional.ofNullable(SecKillTimeId).ifPresent(t -> queryWrapper.eq(SecKillSku::getSecKillTimeId, SecKillTimeId));

        return baseMapper.selectPage(pageParam, queryWrapper);
    }

    /**
     * 批量保存sku并更新为秒杀商品
     */
    @Override
    @Transactional
    public boolean saveBatchBySkuList(List<SecKillSku> SecKillSkuList) {
        this.saveBatch(SecKillSkuList);

        //更新sku为秒杀商品
        List<Long> skuIdList = SecKillSkuList.stream().map(SecKillSku::getSkuId).collect(toList());
        productFeignClient.updateSkuType(skuIdList, SkuType.SEC_KILL);
        return Boolean.TRUE;
    }
}
